import utils from '../utils/index'
import Emitter from '../utils/Emitter'

class Store {
  constructor(initState = {}) {
    if (typeof initState !== 'object') throw new Error('store 的初始状态期待接受的值类型为 Object')

    this.data = initState
  }

  setData(...args) {
    const firstArg = args[0]
    const secondArg = args[1]
    if (args.length === 1 && firstArg instanceof Object) {
      Object.keys(firstArg).forEach((key) => {
        Store.checkKeyTypeisString(key)
        Store.setData(this.data, key, firstArg[key])
      })
    } else {
      Store.checkKeyTypeisString(firstArg)
      Store.setData(this.data, firstArg, secondArg)
    }
    this.emit('update')
  }

  getData(key) {
    return this.data[key]
  }

  remoteData(key) {
    delete this.data[key]
  }

  /**
   *
   * @param {data} target
   * @param {string} key
   * @param {*} value
   * @returns {void}
   */
  static setData(target, key, value) {
    target[key] = value
  }

  /**
   * 检测 key 是否为 string
   * @param key
   */
  static checkKeyTypeisString(key) {
    if (!utils.isStr(key)) throw new TypeError(`${key} expected type is string.`)
  }
}

utils.defaultsDeep(Store.prototype, new Emitter())

export default Store
